package com.ld.businessCard.service.impl;

import com.ld.businessCard.dao.CardDAO;
import com.ld.businessCard.entity.Card;
import com.ld.businessCard.service.CardService;

import java.util.List;

public class CardServiceImpl implements CardService {
	private CardDAO cardDAO = new CardDAO();
	public int addCard(Card card) {
		return cardDAO.insert(card);
	}

	public int deleteCardById(Integer id) {
		Card card = cardDAO.findById(Card.class,id);
		if(card == null) return 0;
		return cardDAO.delete(card);
	}

	public int updateCard(Card card) {
		return cardDAO.update(card);
	}

	public List<Card> getRecycleCardsByUserId(Integer userId){
		return cardDAO.find("from Card C where C.userId = ? and C.status = 1",new Object[]{userId} );
	}

	public List<Card> getCardsByLike(String name) {
		return null;
	}

	public List<Card> getAllCards() {
		return cardDAO.find("from Card C where C.status = 0",new Object[]{});
	}

	public Card getCardById(Integer id) {
		return cardDAO.findById(Card.class,id);
	}


	public int recoverCard(Integer id) {
		Card card = getCardById(id);
		if(card == null) return 0;
		else {
			card.setStatus(0);
			return cardDAO.update(card);
		}
	}


	public List<Card> getMyCards(Integer userId) {
	 	 cardDAO.find("from Card C where C.userId = ? and C.status = 0",new Object[]{userId});
		return cardDAO.find("from Card C where C.userId = ? and C.status = 0",new Object[]{userId});
	}

	public List<Card> getMyValidCards(String account) {
		return null;
	}


	public int changeCard(Card card) {
		return cardDAO.update(card);
	}


	public void exportAllCardsToExcel(List<Card> cards) {

	}

	public int recycleCard(Integer id) {
		Card card = getCardById(id);
		if(card == null) return 0;
		else {
			card.setStatus(1);
			return cardDAO.update(card);
		}
	}

	public List<Card> getAllRecycleCards() {
		return cardDAO.find("from Card C where C.status = 1",new Object[]{});
	}

	public int deleteCardByUserId(Integer userId) {
		List<Card> myCards = getMyCards(userId);
		for (Card myCard : myCards) {
			int i = cardDAO.delete(myCard);
			if(i == 0) return 0;
		}
		return 1;
	}

	public List<Card> getCardsByLikeName(String name, Integer userId) {
		if(userId == null) {
			return cardDAO.find("from Card C where C.name like ?",new Object[]{"%" + name + "%"});
		}else {
			return cardDAO.find("from Card C where C.userId = ? and C.name like ?",new Object[]{userId,"%" + name + "%"});
		}
	}

}
